package core

import (
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
	"uni-crawl-frame/core/livedto"
	"uni-crawl-frame/core/tvdto"
	"uni-crawl-frame/core/voddto"
	"uni-crawl-frame/core/webdriverdto"
	"uni-crawl-frame/db/mysql/model/entity"
	"uni-crawl-frame/service/configservice"
	"uni-crawl-frame/utils/ffmpegutil"
	"uni-crawl-frame/utils/httputil"
)

type ApplicationContext struct {
	// 基础部分Context
	Log           *glog.Logger
	CrawlStrategy // 绑定策略
	webdriverdto.CrawlWebDriverCtx

	// 业务部分Context
	CrawlQueueSeed *entity.CmsCrawlQueue // 视频抓取队列
	CrawlVodCtx    *voddto.CrawlVodCtx   // 点播抓取上下问
	CrawlLiveCtx   *livedto.CrawlLiveCtx // 直播抓取上下文
	CrawlTVCtx     *tvdto.CrawlTVCtx     // TV抓取上下文
}

type CrawlStrategy struct {
	RetryFlow int // 当前策略是否需要整体流程重试
	CrawlByBrowserInterface
}

func GetInitedCrawlContext() *ApplicationContext {
	ctx := new(ApplicationContext)
	ctx.Log = g.Log().Line()

	ctx.CrawlBrowserDto = configservice.GetCrawlBrowser()
	ctx.CrawlBrowserInfoDto = configservice.GetCrawlBrowserInfo()

	ctx.CrawlVodCtx = new(voddto.CrawlVodCtx)
	ctx.CrawlLiveCtx = new(livedto.CrawlLiveCtx)
	ctx.CrawlTVCtx = new(tvdto.CrawlTVCtx)
	return ctx
}

// 抓取点播接口集合
type CrawlVodFlowInterface interface {
	CrawlByBrowserInterface

	// 下载视频接口集合
	ConvertM3U8(seed *entity.CmsCrawlQueue, filePath string) (*ffmpegutil.M3u8DO, error)
	ConvertM3U8GetBaseUrl(m3u8Url string) string
	DownLoadToMp4(m3u8DO *ffmpegutil.M3u8DO) error
}

type AbstractCrawlVodFlow struct {
	CrawlByBrowserInterface
	*AbstractCrawlByBrowser
}

func (r *AbstractCrawlVodFlow) UseBrowser() bool {
	return true
}

func (r *AbstractCrawlVodFlow) UseMobileUA() bool {
	return false
}

func (r *AbstractCrawlVodFlow) UseCrawlerProxy() bool {
	return false
}

func (r *AbstractCrawlVodFlow) UseBrowserMobProxy() bool {
	return true
}

func (r *AbstractCrawlVodFlow) OpenBrowser(ctx *ApplicationContext) {
}

func (r *AbstractCrawlVodFlow) OpenBrowserWithParams(ctx *ApplicationContext, json *gjson.Json) {
}

func (r *AbstractCrawlVodFlow) FillTargetRequest(ctx *ApplicationContext) {
}

func (r *AbstractCrawlVodFlow) ConvertM3U8(seed *entity.CmsCrawlQueue, filePath string) (*ffmpegutil.M3u8DO, error) {
	baseUrl := r.ConvertM3U8GetBaseUrl(seed.CrawlM3U8Url)
	return ffmpegutil.ConvertM3U8(seed.CrawlM3U8Url, baseUrl, filePath)
}

func (r *AbstractCrawlVodFlow) ConvertM3U8GetBaseUrl(m3u8Url string) string {
	return httputil.GetBaseUrlBySchema(m3u8Url)
}

func (r *AbstractCrawlVodFlow) DownLoadToMp4(m3u8DO *ffmpegutil.M3u8DO) error {
	return ffmpegutil.DownloadToMp4(m3u8DO)
}
